<template>
    <CommonDialog :visible="visible" width="680px" @on-close="cancel" :title="formData.homeworkId ? '编辑作业' : '添加作业'">
        <el-form ref="editRef" :model="formData" :rules="formRule" :label-width="88" class="home-form">
            <el-form-item label="作业名称" prop="name" class="srt-el-input-item">
                <el-input show-word-limit maxlength="50" type="text" v-model="formData.name"
                    @keyup.enter="confirm" class="srt-el-input" placeholder="请输入作业名称，最多50个字" style="width: 534px;">
                </el-input>
            </el-form-item>
            <el-form-item label="作业描述" prop="context" class="srt-el-input-item form-mb20">
                <el-input show-word-limit maxlength="500" :rows="5" type="textarea" v-model="formData.context"
                    @keyup.enter="confirm" class="srt-el-textarea" placeholder="请输入作业描述，可以填写作答要求等描述，最多500个字" style="width: 534px;">
                </el-input>
            </el-form-item>
            <el-form-item label="作业附件" prop="materialList" class="srt-el-input-item form-mb20">
                <div>
                    <div>
                        <el-button class="srt-el-button srt-el-button-h36 file-btn" @click="handleAdd">选择文件</el-button>
                        <span class="input-desc">多个文件可打包上传</span>
                    </div>
                    <div class="home-file" v-if="formData.materialList?.length">
                        <FileItem v-for="item in formData.materialList" :key="item.materialId" :fileData="item" delOp @handle-del="handleDel"></FileItem>
                    </div>
                </div>
            </el-form-item>
            <!-- <el-form-item label="作业要求" prop="times" class="srt-el-input-item form-mb20">
                <span class="input-tip">可提交次数</span>
                <el-input show-word-limit type="text" v-model="formData.times"
                    @keyup.enter="confirm" class="srt-el-input input-width" placeholder="请输入提交次数">
                </el-input>
                <span class="input-desc">即学员可以重复作答该作业的次数，至少1次。</span>
            </el-form-item> -->
            <el-form-item label="是否必做" prop="compulsory" class="srt-el-input-item">
                <el-radio-group v-model="formData.compulsory" class="setting">
                    <el-radio :label="1" size="large" class="srt-el-radio">是</el-radio>
                    <el-radio :label="0" size="large" class="srt-el-radio">否</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <div class="dialog-footer">
            <el-button class="srt-el-button srt-el-button--cancel srt-el-button-h36" @click="cancel">取消</el-button>
            <el-button class="srt-el-button srt-el-button--primary srt-el-button-h36" @click="confirm">确定</el-button>
        </div>
        <!-- 素材库 -->
        <yanxiu-material-dialog
            v-model="addVisible"
            :mode="1"
            usableMode="none"
            previewEnable
            showMyMaterial
            @on-ok="fileInsert"
        />
    </CommonDialog>
</template>

<script setup>
import YanxiuMaterialDialog from '@/components/yanxiu-material-dialog.vue';
import FileItem from './file-item.vue';
import CommonDialog from '@/components/common-dialog.vue'
import { ref, watch, computed } from 'vue';
import { useRoute } from 'vue-router';
import { deepCopy } from '@yanxiu/lib';


const route = useRoute();

const emit = defineEmits(['update:modelValue', 'refresh']);

const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
    form: {
        type: Object,
        default: () => {
            return {};
        }
    },
    list: { // 作业list
        type: Array,
        default: () => {
            return [];
        }
    }
});


const formRule = ref({
    name: [
        {
            required: true,
            validator: (rule, value, callback) => {
                let temp = value && value.trim() || '';
                if (temp.length > 50 || temp.length < 2) {
                    callback('请输入2-50个字的作业名称');
                }else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    // times: [
    //     {
    //         type: 'number',
    //         message: '请输入1-10的整数',
    //         trigger: 'blur',
    //         transform(value) {
    //             let temp = Number(value);
    //             if (!/^\d{1,10}$/.test(temp) || temp > 10 || temp < 1) {
    //                 return true;
    //             }
    //         }
    //     }
    // ]
});

const visible = computed({
    get: () => props.modelValue,
    set: val => {
        emit('update:modelValue', val);
    }
})

const formData = ref({
    compulsory: 1,
    times: -1
})

// 素材库对话框
const addVisible = ref(false);

const editRef = ref(null);


watch(() => props.modelValue, (val) => {
    if (val) {
        let temp = props.form && deepCopy(props.form) || {};
        let materialInfoList = temp.homeworkMaterialList?.length && temp.homeworkMaterialList.map(item => item.materialVo) || [];
        formData.value = Object.assign({ compulsory: 1, times: -1}, temp, {materialList: materialInfoList});
    }else {
        editRef.value && editRef.value.resetFields();
    }
})



// 选择素材
async function fileInsert(fileList) {
    if (!fileList[0]) {
        return;
    }
    formData.value.materialList = fileList;
}

// 添加文件
function handleAdd() {
    addVisible.value = true;
}


function handleDel() {
    formData.value.materialList = [];
}

function cancel () {
    emit('update:modelValue', false);
}



function confirm () {
    let homeList = props.list?.length && props.list.map((item, index) => {
         item.sort = index + 1;
         return item;
    }) || [];
    let materialIdList = formData.value.materialList?.length && formData.value.materialList.map(item => item.materialId) || [];
    let params = {compulsory: formData.value.compulsory, context: formData.value.context, name: formData.value.name, materialIdList: materialIdList, times: -1};
    if(formData.value.homeWorkId) {
        let index = props.list.findIndex(item => item.homeWorkId === formData.value.homeWorkId);
        params.sort = homeList[index].sort;
        params.homeWorkId = formData.value.homeWorkId;
        homeList[index] = params;
    }else {
        params.sort = homeList.length + 1;
        homeList.push(params);
    }

    editRef.value.validate((valid) => {
        if (!valid) {
            G_dispatchEvent('toast', { message: '请检查必填信息', type: 'error' })
            return;
        }
        G_transmit('homeworkAdd', {
            data: {
                homeWorkInsertInfoRequestList: [
                    ...homeList,
                ],
                moocId: route.params.moocId,
            }
        }).then((res) => {
            cancel();
            G_dispatchEvent('toast', { message: '保存成功', type: 'success'});
            emit('refresh');
        }).catch((_err) => {
            console.log(_err)
        })
    })
}

</script>

<style lang="scss" scoped>
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
}
.home-form {
     :deep(.el-form-item) {
        margin-bottom: 30px;
    }

    :deep(.el-form-item__label) {
        line-height: 40px;
        height: 40px;
        color: var(--srt-color-gray);
        margin-right: 8px;
    }
    .input-tip {
        font-size: 14px;
        color: var(--srt-main-text-color);
        margin-right: 12px;
    }
    .file-btn {
        width: 86px;
    }
    .input-width {
        width: 80px;
        :deep(.el-input__wrapper .el-input__inner) {
            height: 34px;
        }
    }
    .input-desc {
        color: var(--srt-color-gray);
        font-size: 12px;
        margin-left: 10px;
    }
    .home-file {
        margin-top: 16px;
        width: 534px;
    }
    :deep(.srt-el-textarea) {
        .el-textarea__inner {
            padding: 12px;
        }
    }
    .form-mb20 {
        margin-bottom: 20px;
    }
}
</style>